#include "signalcontainer.h"
#include "exceptions.h"

SignalContainer::SignalContainer()
{
    this->source = NULL;
    this->label = "";
    this->sortIndex = 0;
    this->capacity = 0;
}

SignalContainer::SignalContainer(BaseElement *source)
{
    this->source = source;
    this->label = source->name;
    this->capacity = 0;
}

int SignalContainer::getCapacity()
{
    return this->capacity;
}

void SignalContainer::addSignal(signed char signal)
{
    Interval t;
    t.signal = signal;
    t.time = 1;
    addInterval(t);
}

//Добавляем строку с сигналами
void SignalContainer::addSignals(QString signal_string)
{
    for (int i = 0; i < signal_string.count(); i++)
    {
        QString signal = signal_string.at(i);
        if ((signal == "1") || (signal == "0"))
            addSignal(signal.toInt());
    }
}

void SignalContainer::addInterval(Interval t)
{
    // Если список пуст или сигнал последнего интервала отличен от добавляемого
    int count = this->signalsArray.count();
    if(count == 0 || this->signalsArray[count-1].signal != t.signal)
    {
        // Добавляем интервал
        this->signalsArray.append(t);
    }
    else
    {
        // Иначе увеличиваем продолжительность интервала
        this->signalsArray[count-1].time += t.time;
    }
    this->capacity += t.time;
}

signed char SignalContainer::at(int index)
{
    if ((index < 0) || (index > capacity))
        throw ArrayIndexError();

    int interval = 0;
    while(index >= this->signalsArray[interval].time)
    {
        index -= this->signalsArray[interval].time;
        interval++;
    }

    return this->signalsArray[interval].signal;
}

void SignalContainer::clear()
{
    this->signalsArray.clear();
    this->capacity = 0;
}

const QVector<Interval>& SignalContainer::getItems()
{
    return this->signalsArray;
}
